// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import GameEvent from "../../Commons/GameEvent";
import GiftManager, { GiftEvent } from "../../Models/Gifts/GiftManager";
import BaseUI from "../BaseUI";
import GiftItem from "../UIItems/GiftItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GiftUI extends BaseUI {

    @property(cc.Animation)
    bgAnim: cc.Animation = null;
    @property([cc.Toggle])
    toggleBtns: cc.Toggle[] = [];
    @property([GiftItem])
    giftItems: GiftItem[] = [];
    @property(cc.Label)
    priceTxt: cc.Label = null;
    @property(cc.Button)
    buyBtn: cc.Button = null;
    @property(cc.Node)
    finishNode: cc.Node = null;

    currentIndex: string = "0";
    protected onLoad(): void {
        this.bgAnim.play("GiftBg0");
        this.currentIndex = "0";
        this.finishNode.active = false;
    }

    protected onEnable(): void {

        this.drawView();
        this.drawBuyState();
        GameEvent.eventNode.on(GiftEvent.BUYGIFT_EVENT, this.onBuyGift, this);
    }

    protected onDisable(): void {
        GameEvent.eventNode.off(GiftEvent.BUYGIFT_EVENT, this.onBuyGift, this);
    }
    onBuyGift() {
        this.drawBuyState();
    }

    drawBuyState() {
        var giftArr = GiftManager.single.getGiftArr();
        this.buyBtn.node.active = !giftArr[Number(this.currentIndex)];
        this.finishNode.active = giftArr[Number(this.currentIndex)];
    }

    drawView() {
        this.bgAnim.play("GiftBg" + this.currentIndex);
        var arr = GiftManager.single.configArr;
        var configObj = arr[Number(this.currentIndex)];
        this.priceTxt.string = "￥" + configObj.price;

        var rewardArr: string[] = configObj.reward.split(",");


        for (let i = 0; i < this.giftItems.length; i++) {
            if (i < rewardArr.length) {
                this.giftItems[i].node.active = true;
                var rewarIds: string[] = rewardArr[i].split(":");
                this.giftItems[i].drawItem(rewarIds[2], rewarIds[3]);

            } else {
                this.giftItems[i].node.active = false;
            }

        }
    }

    buyClick() {
        GiftManager.single.requestBuy(this.currentIndex);
    }

    toggleClick(e, index: string) {
        if (this.currentIndex == index) {
            return;
        }
        this.currentIndex = index;

        this.drawView();
    }
}
